23
Build Your Own Game—Tic Tac Toe
23
Although we have defined defaults for the textbox fields that track the scores, it
is necessary to reset them at the end of each game so we can play a new game—the
default only works once when we launch the program.
Let me explain how the
UserForm1.Controls(“TextBox” & (i − 1) * 3 + j) = ““ works.
Notice that I have put it in a double for loop so that it repeats nine times.
By using the formula (i − 1) * 3 + j we are able to generate a number from 1 to 9.
This is an indirect way to write the nine variable names (UserForm1.Controls.TextBox1,
…, …, …, UserForm1.Controls.TextBox9) making the code much more compact.
Now that the form is visible, we need code to play the game.
Go back to the form and double-click on the “Play” button.
Enter the following code.
Private Sub CommandButton1_Click()
UserForm1.Controls("TextBox10") = ""
Call InitForm
RandomValue = Int((9 * Rnd) + 1)
If UserForm1.TextBox10 = "" Then
If UserForm1.OptionButton1 = True Then
UserForm1.Controls("TextBox" & RandomValue) = "O"
End If
End If
End Sub
FIGURE 2.21 CommandButton1.
InitForm is defined in Module1 and its main purpose is to turn all cells white and
get rid of the noughts and crosses from the previous game. See code below.
The Random statement creates a random number from 1 to 9 and places a “O” in
that cell. This is only used if the computer plays first. The subsequent moves by the
computer require further sophistication and will be explained later.
Sub InitForm()
Dim cCont As Control
For i = 1 To 3
For j = 1 To 3
UserForm1.Controls("TextBox" & (i - 1) * 3 + j) = ""
UserForm1.Controls("TextBox" & (i - 1) * 3 + j).BackColor = &HFFFFFF
Next j
Next i
End Sub
FIGURE 2.22 InitForm.